import { Component, OnInit, ElementRef, ViewChild, Inject, PLATFORM_ID } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { NzNotificationService } from 'ng-zorro-antd';
import { MessageService } from 'primeng/api';
import { AuthService } from 'src/app/service/auth.service';
import { JsonResult } from 'src/app/model/JsonResult';
import { SysUserService } from 'src/app/service/sys-user.service';
import { isPlatformBrowser } from '@angular/common';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers:[MessageService]
})
export class LoginComponent implements OnInit {

  loginForm:FormGroup;

  @ViewChild("userid",{static:false})
  private userid_er:ElementRef

  @ViewChild('ctl_pwd',{ static:false }) 
  ctl_pwd: ElementRef;

  private userid$ = new Subject();

  constructor(
    private fb:FormBuilder,
    private noti:NzNotificationService,
    private msgService:MessageService,
    private authService:AuthService,
    private userService:SysUserService,
    @Inject(PLATFORM_ID)
    private platformId: Object
  ) { 
    this.initLoginForm();// 初始化登录表单
    // this.initRx();// 初始化 rx 对象
  }

  ngOnInit() {
  }

  initLoginForm(){
    this.loginForm = this.fb.group({
      userid:[null,Validators.required],
      userName:[{value:null,disabled:true},Validators.required],
      password:[null,Validators.required]
    });

    // this.loginForm.controls.password.valueChanges.subscribe(
    //   res => console.log(res),
    //   error => this.primeMsg('输入密码时出现异常！')
    // )
    // this.log('登录表单初始化完毕！');
    // this.log(this.loginForm.value);
    // this.primeMsg('初始化完毕！');
  }


  // 注册 rx 类型的对象
  initRx(){
    this.userid$.pipe(debounceTime(1000)).subscribe(
      (val:string) => {
        this.userService.selectByUserId(val).subscribe(
          ( jr:JsonResult ) =>{
            if( jr.code !==1 ){
              console.log(jr);
              this.primeMsg(jr.msg);
              return
            }

            this.authService.user = jr.data;
            // this.loginForm.patchValue({...{ 'userid':jr.data.userid,'userName':jr.data.username,'password':'' }});
            this.loginForm.patchValue({...{ 'userName':jr.data.username }});
            console.log('查询用户得到的数据时：');
            console.log(this.authService.user);
          },error => this.primeMsg('查询用户时出现异常！')
        )

        // this.primeMsg('工号：' + val);
      }
    )
  }

  getUser(ctl_pwd:string){
    const userId:string = this.loginForm.controls.userid.value;
    this.userService.selectByUserId(userId).subscribe(
      ( jr:JsonResult ) =>{
        if( jr.code !==1 ){
          this.primeMsg(jr.msg);
          return
        }

        if( jr.data && jr.data.username ){
          this.loginForm.patchValue({...{ 'userName':jr.data.username }});
          this.focusPWD(ctl_pwd);
          this.primeMsg('查询到了用户信息！');
        }else{
          this.primeMsg('没有查询到用户信息！');
        }
      },error => this.primeMsg('查询获取用户信息时出现异常！')
    )
  }


  useridChange(e){
    this.userid$.next(e);
  }


  // 登录表单提交
  submitForm(){
    let userid = this.loginForm.value["userid"];
    let password = this.loginForm.value["password"];

    
    this.authService.login(userid,password).subscribe(
      (res:JsonResult)=> {
        if( !res ){
          this.primeMsg("返回数据异常！");
          return;
        }

        if( res.code !== 1 ){
          this.primeMsg("账号或密码错误！");
          return;
        }

        // 登录成功则跳转到首页
        this.authService.isLoggedIn = true;
        this.primeMsg("登录成功！");
        this.authService.gotoIndex();
        
      },error=>this.primeMsg("登录失败！")
    )
  }

  // 登录
  login(){
    console.log(this.loginForm.value);
    
    const userId:string = this.loginForm.controls.userid.value;
    const pw:string = this.loginForm.controls.password.value
    console.log('即将发送给服务的两个参数依次是：' + userId + ',' + pw);
    this.authService.login(userId,pw).subscribe(
      ( jr:JsonResult ) =>{
        if( jr.code !==1 ){
          this.primeMsg(jr.msg);
          return
        }

        this.primeMsg('登录成功！');
      },error => this.primeMsg('登录时出现异常！')
    )
  }

  // 自定义渐变色消息通知
  primeMsg(content:string) {
    this.msgService.add({key: 'custom', severity:'info', summary: '通知', detail:content});
  }

  log(content:string){
    console.log(content);
  }

  // 设置密码 input 为当前焦点
  focusPWD(ctlId:string){
    console.log('即将设置' + ctlId + '为焦点控件');
    if (isPlatformBrowser(this.platformId)) {
      // this[ctlId].nativeElement.focus();
      this[ctlId].nativeElement.focus();
      this[ctlId].nativeElement.select();
    }
  }

}
